﻿// ===============================================================================
// DotNet.Platform 开发框架 2016 版权所有
// ===============================================================================

using System;
using DotNet.Edu.Entity;
using DotNet.Collections;
using DotNet.Extensions;
using DotNet.Helper;
using DotNet.Utility;
using System.Collections.Generic;
using System.Linq;

namespace DotNet.Edu.Service
{
    /// <summary>
    /// 安全培训资料上报服务
    /// </summary>
    public class AqpxFileService
    {
        /// <summary>
        /// 审核
        /// </summary>
        /// <param name="entity">实体</param>
        public BoolMessage Audit(AqpxFile entity)
        {
            var repos = new AqpxRepository<AqpxFile>();
            repos.Update(entity, new[] { "status", "remark" });

            if (entity.status == 2)
            {
                var aqpxEntity = repos.Get(entity.id);
                var studentRepos = new EduRepository<Student>();
                var hasStudent = studentRepos.Exists(p => p.IDCardNo == aqpxEntity.id_number && p.Status != 5);
                if (!hasStudent)
                {
                    #region 添加学员信息
                    var student = new Student();
                    student.Id = StringHelper.Guid();
                    student.Name = aqpxEntity.name;
                    student.IDCardNo = aqpxEntity.id_number;
                    student.Spell = SpellHelper.GetSpell(student.Name);
                    student.Sex = IDCardHelper.GetSexName(student.IDCardNo);
                    student.Password = StringHelper.EncryptString(student.IDCardNo.Substring(student.IDCardNo.Length - 6));
                    student.DrivingModel = "A1";
                    student.MobilePhone = aqpxEntity.phone;
                    student.WorkCategoryId = "1";
                    student.WorkCategoryName = "两类人考试培训科目";
                    student.TrainCycle = 1;
                    student.RegDateTime = DateTime.Now;
                    student.CreateDateTime = DateTime.Now;
                    student.Status = 1;
                    student.SchoolId = "eb16d125619642eab48cccc5c024d837";
                    student.SchoolName = "西安市交通职业培训中心";
                    student.TotalPeriod = 0;
                    student.Note = "微信报名";
                    //student.TrainGroupId = aqpxEntity.plan_id;
                    //student.TrainGroupName = aqpxEntity.plan_name;
                    //student.ReservationDateTime = aqpxEntity.reservation_date_time;

                    studentRepos.Insert(student);
                    #endregion
                }
            }

            return BoolMessage.True;
        }

        public BoolMessage UpdatePlanInfo(string id_number, string plan_id, string plan_name)
        {
            var repos = new AqpxRepository<AqpxFile>();
            var entity = new AqpxFile();
            //entity.plan_id = plan_id;
            //entity.plan_name = plan_name;
            repos.Update(entity, p => p.id_number == id_number, new[] { "plan_id", "plan_name" });
            return BoolMessage.True;
        }

        public BoolMessage UpdatePayStatus(string id)
        {
            var repos = new AqpxRepository<AqpxFile>();
            

            var model = repos.Get(id);
            if (model.pay_status == 1)
            {
                return new BoolMessage(false,"此学员已支付");
            }

            var sql = "update aqpx_file set pay_status=1,pay_msg='线下支付',pay_date_time=getdate() where id=@id";
            try
            {
                decimal fee=(decimal)0.00;
                var feeStr = Auth.Service.AuthService.Param.GetByCode("AqpxFee").Value;//repos.Database.ExecuteScalar<decimal?>("SELECT value FROM[dbo].sys_param WHERE code = 'aq-qx-gly'");
                if (feeStr is null)
                {
                    return new BoolMessage(false, "系统参数表缺少培训费用参数（Code: AqpxFee)");
                }

                if(!decimal.TryParse(feeStr, out fee))
                {
                    return new BoolMessage(false, "系统参数表培训费用参数（Code: AqpxFee)值非法:{0}".FormatString(feeStr));
                }


                repos.Database.BeginTransaction();
                var count = repos.Database.Execute(sql, new { id });

                #region 插入一条线下支付订单数据
                if(count>0)
                {
                    sql = @"INSERT INTO dbo.aqpx_pay_order
                        (
                            id,
                            name,
                            id_card,
                            phone,
                            order_type,
                            open_id,
                            transaction_id,
                            out_trade_no,
                            total_fee,
                            body,
                            client_ip,
                            time_start,
                            time_expire,
                            confirmed,
                            trade_state,
                            trade_state_desc,
                            trade_end_time,
                            create_date_time
                        )
                        VALUES
                        (
                            @id,
                            @name,
                            @id_card, 
                            @phone,
                            '1',
                            @open_id, 
                            NULL,
                            '',
                            @total_fee, 
                            '西安市交通职业培训中心-安全两类人培训费',
                            '',
                            '', 
                            '', 
                            1,
                            'SUCCESS', 
                            '支付成功', 
                            NULL, 
                            @create_date_time
                        );";
                    var id_PayOrder = new DotNet.Framework.Helper.IdWorkerHelper(10L).nextId();
                    var total_fee = Convert.ToInt32(fee) * 100;
                    var dtNow = System.DateTime.Now;
                    repos.Database.Execute(sql, new { id = id_PayOrder, model.name, id_card = model.id_number, model.phone, model.open_id, total_fee, create_date_time = dtNow });
                    repos.Database.CommitTransaction();
                }
                else
                {
                    repos.Database.RollbackTransaction();
                    return new BoolMessage(false, "更新报名支付状态失败，未找到报名信息!");
                }
                #endregion
            }
            catch (Exception ex)
            {
                repos.Database.RollbackTransaction();
                throw ex;
            }

            return BoolMessage.True;
        }


        public BoolMessage UpdateExamDate(string id,DateTime? examDate)
        {
            var repos = new AqpxRepository<AqpxFile>();

            var sql = "update aqpx_file set exam_date=@exam_date where id=@id";
            var count = repos.Database.Execute(sql, new { id,exam_date = examDate });

            return BoolMessage.True;
        }

        /// <summary>
        /// 删除对象
        /// </summary>
        /// <param name="ids">主键数组</param>
        public BoolMessage Delete(string[] ids)
        {
            var repos = new AqpxRepository<AqpxFile>();
            repos.Delete(ids);
            return BoolMessage.True;
        }

        /// <summary>
        /// 获取对象
        /// </summary>
        /// <param name="id">主键</param>
        public AqpxFile Get(string id)
        {
            return new AqpxRepository<AqpxFile>().Get(id);
        }

        /// <summary>
        /// 获取对象分页集合
        /// </summary>
        /// <param name="pageCondition">分页对象</param>
        /// <param name="key">关键字</param>
        /// <param name="status">状态</param>
        /// <param name="industry_category">行业类别</param>
        /// <param name="start_exam_date">考试开始时间</param>
        /// <param name="end_exam_date">考试结束时间</param>
        public PageList<AqpxFile> GetPageList(PaginationCondition pageCondition, string key, string status,
            string industry_category,string user_category, string start_exam_date, string end_exam_date)
        {
            pageCondition.SetDefaultOrder(nameof(AqpxFile.operate_date_time));
            var repos = new AqpxRepository<AqpxFile>();
            var query = repos.PageQuery(pageCondition);

            if (key.IsNotEmpty())
            {
                key = key.Trim();
                query.Where(p => p.name.Contains(key) || p.id_number.Contains(key) || p.phone.Contains(key));
            }
            if (status != null && status.Trim().IsNotEmpty())
            {
                status = status.Trim();
                var statusInt = status.ToInt(0);
                query.Where(p => p.status == statusInt);
            }
            if (industry_category.IsNotEmpty())
            {
                query.Where(p => p.industry_category == industry_category);
            }
            if (user_category.IsNotEmpty())
            {
                query.Where(p => p.user_category == user_category);
            }
            if (start_exam_date.IsNotEmpty())
            {
                var startDate = start_exam_date.ToDateTime();
                query.Where(p => p.exam_date >= startDate);
            }
            if (end_exam_date.IsNotEmpty())
            {
                var endDate = end_exam_date.ToDateTime();
                query.Where(p => p.exam_date <= endDate);
            }
            return repos.Page(query);
        }


        /// <summary>
        /// 获取启用的对象集合(已排序)
        /// </summary>
        public List<AqpxFile> GetList()
        {
            var repos = new AqpxRepository<AqpxFile>();
            var query = repos.SQL.OrderByDesc(p => p.operate_date_time);
            return repos.Query(query).ToList();
        }
    }
}
